package com.bjyhl.ui.refresh;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bjyhl.core.net.callback.IError;
import com.bjyhl.core.net.callback.IFailure;
import com.bjyhl.ui.recycler.MultipleItemEntity;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.bjyhl.core.app.Latte;
import com.bjyhl.core.net.RestClient;
import com.bjyhl.core.net.callback.ISuccess;
import com.bjyhl.ui.recycler.DataConverter;
import com.bjyhl.ui.recycler.MultipleRecyclerAdapter;

import java.util.ArrayList;

public class RefreshHandler implements
        SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener {

    private static final String TAG = "RefreshHandler";
    private final SwipeRefreshLayout REFRESH_LAYOUT;
    private final PagingBean BEAN;
    private final RecyclerView RECYCLERVIEW;
    private MultipleRecyclerAdapter mAdapter = null;
    private final DataConverter CONVERTER;
    private String url = null;
    private boolean canLoadMore = true;

    private RefreshHandler(SwipeRefreshLayout refreshLayout,
                           RecyclerView recyclerView, DataConverter dataConverter, PagingBean bean, String url, int pageSize, boolean canLoadMore) {
        this.REFRESH_LAYOUT = refreshLayout;
        this.RECYCLERVIEW = recyclerView;
        this.CONVERTER = dataConverter;
        bean.setPageSize(pageSize);
        this.BEAN = bean;
        this.url = url;
        this.canLoadMore = canLoadMore;
        REFRESH_LAYOUT.setOnRefreshListener(this);
    }

    public static RefreshHandler create(SwipeRefreshLayout swipeRefreshLayout,
                                        RecyclerView recyclerView,
                                        DataConverter converter,
                                        String url) {
        return new RefreshHandler(swipeRefreshLayout, recyclerView, converter, new PagingBean(), url, 20, true);
    }

    public static RefreshHandler create(SwipeRefreshLayout swipeRefreshLayout,
                                        RecyclerView recyclerView,
                                        DataConverter converter,
                                        String url,
                                        boolean canLoadMore) {
        return new RefreshHandler(swipeRefreshLayout, recyclerView, converter, new PagingBean(), url, 20, canLoadMore);
    }

    public static RefreshHandler create(SwipeRefreshLayout swipeRefreshLayout,
                                        RecyclerView recyclerView,
                                        DataConverter converter,
                                        String url, int pageSize, boolean canLoadMore) {
        return new RefreshHandler(swipeRefreshLayout, recyclerView, converter, new PagingBean(), url, pageSize, canLoadMore);
    }

    @Override
    public void onRefresh() {
        // TODO 下拉刷新
//        mAdapter.notifyItemRangeRemoved(0, BEAN.getCurrentCount());
////        RECYCLERVIEW.swapAdapter(mAdapter, true);
//        Log.e(TAG, "onRefresh: @@@@XXX" + mAdapter.getData().size());
//        BEAN.setPageIndex(0).setCurrentCount(0).setTotal(0);


        REFRESH_LAYOUT.setRefreshing(true);
        Latte.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                firstPage();
                REFRESH_LAYOUT.setRefreshing(false);
            }
        }, 100);
    }

    public void firstPage() {
        final String reqUrl = url + (!canLoadMore ? "" : BEAN.getPageIndex() + "/" + BEAN.getPageSize());



        RestClient.builder()
                .url(reqUrl)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        LogUtils.d("首页数据" + response);
                        final JSONObject object = JSON.parseObject(response);

                        //设置Adapter
                        mAdapter = MultipleRecyclerAdapter.create(CONVERTER.setJsonData(response));
                        mAdapter.setOnLoadMoreListener(RefreshHandler.this, RECYCLERVIEW);
                        RECYCLERVIEW.setAdapter(mAdapter);

                        if(canLoadMore) {
                            BEAN.setTotal(object.getInteger("total"));
                            BEAN.setCurrentCount(mAdapter.getData().size());
                            BEAN.addIndex();
                        } else {
                            // 不可加载更多
                            mAdapter.loadMoreEnd();
                        }
                    }
                })
                .failure(new IFailure() {
                    @Override
                    public void onFailure() {
                        Log.e(TAG, "onFailure: ");
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        Log.e(TAG, "onError: " + code + "@" + msg);
                    }
                })
                .build()
                .get();
    }

    @Override
    public void onLoadMoreRequested() {
        final int pageSize = BEAN.getPageSize();
        final int currentCount = BEAN.getCurrentCount();
        final int total = BEAN.getTotal();

        if (mAdapter.getData().size() < pageSize || currentCount >= total) {
            mAdapter.loadMoreEnd();
        } else {
            Latte.getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    RestClient.builder()
                            .url(url + BEAN.getPageIndex() + "/" + BEAN.getPageSize())
                            .success(new ISuccess() {
                                @Override
                                public void onSuccess(String response) {
                                    LogUtils.json("首页刷新第" + BEAN.getPageIndex() + "页", response);
                                    mAdapter.setNewData(CONVERTER.setJsonData(response).convert());
                                    //累加数量
                                    BEAN.setCurrentCount(mAdapter.getData().size());
                                    mAdapter.loadMoreComplete();
                                    BEAN.addIndex();
                                }
                            })
                            .build()
                            .get();
                }
            }, 0);
        }
    }
}
